import axios from 'axios'
import qs from 'qs'
import { ElMessage } from 'element-plus'
import router from '@/router'

const service = axios.create({
  baseURL: 'http://localhost:8080',
  timeout: 5000,
  withCredentials: true
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    const token = sessionStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = token
    }
    
    // 根据不同的接口使用不同的数据格式
    if (config.url === '/UserController/login') {
      config.headers['Content-Type'] = 'application/json'
    } else if (config.method?.toLowerCase() === 'post') {
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
      if (typeof config.data === 'object' && !(config.data instanceof FormData)) {
        config.data = qs.stringify(config.data)
      }
    }

    return config
  },
  error => {
    console.error('请求错误：', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => response,
  error => {
    console.error('Response error:', error.response || error)
    
    if (error.response?.status === 403) {
      if (error.config.url === '/UserController/register') {
        ElMessage.error('该手机号已被注册')
      } else if (error.config.url === '/UserController/login') {
        ElMessage.error('用户名或密码错误')
      } else {
        sessionStorage.removeItem('token')
        sessionStorage.removeItem('user')
        ElMessage.error('登录已过期，请重新登录')
        router.push('/login')
      }
    }
    return Promise.reject(error)
  }
)

export default service 